package com.qiaofang.applet.service.member.service.impl;

import com.qiaofang.applet.common.base.MongoBaseService;
import com.qiaofang.applet.common.util.RedisKeyUtil;
import com.qiaofang.applet.common.util.RedisUtil;
import com.qiaofang.applet.service.member.domain.Department;
import com.qiaofang.applet.service.member.repository.DepartmentRepository;
import com.qiaofang.applet.service.member.service.DepartmentService;
import com.qiaofang.applet.service.member.service.dto.DeptSimpleListDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DepartmentServiceImpl extends MongoBaseService<Department, String> implements DepartmentService {
    private final DepartmentRepository repository;

    @Autowired
    private RedisUtil redisUtil;

    public DepartmentServiceImpl(DepartmentRepository repository) {
        super(repository);
        this.repository = repository;
    }

    @Override
    public Department findByDeptUuidAndCompanyUuid(String deptUuid, String companyUuid) {
        return repository.findByDeptUuidAndCompanyUuid(deptUuid, companyUuid);
    }

    @Override
    public void removeDeptCache(String corporationCode, String companyUuid) {
        redisUtil.hdel(RedisKeyUtil.getDeptMapKey(corporationCode, companyUuid));
    }

    @Override
    public String getDeptName(String corporationCode, String companyUuid, String deptUuid){
        String deptMapKey = RedisKeyUtil.getDeptMapKey(corporationCode, companyUuid);
        Object obj = redisUtil.hget(deptMapKey, deptUuid);
        if (obj != null){
            return (String) obj;
        }
        Department department = repository.findByCorporationCodeAndCompanyUuidAndDeptUuid(corporationCode, companyUuid, deptUuid);
        if (department == null){
            return "";
        }
        redisUtil.hsetDayEnd(deptMapKey, deptUuid, department.getDeptName());
        return department.getDeptName();
    }

    @Override
    public List<DeptSimpleListDto> getDeptList(String corporationCode, String cityCode) {
        return repository.findAllByCorporationCodeAndCityCode(corporationCode, cityCode);
    }

    @Override
    public Map<String, String> getDeptMap(String corporationCode, String companyUuid) {
        List<DeptSimpleListDto> list = repository.findAllByCorporationCodeAndCompanyUuid(corporationCode, companyUuid);
        Map<String, String> deptMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(list)){
            deptMap = list.stream().collect(Collectors.toMap(DeptSimpleListDto::getDeptUuid, DeptSimpleListDto::getDeptName, (k1, k2) -> k1));
        }
        return deptMap;
    }


}
